"""
#作者：cacho_37967865
#博客：https://blog.csdn.net/sinat_37967865
#文件：file_deal.py
#日期：2019-08-29
#备注：保存TXT和其他文件内容
"""

import math
import os

# 只写，覆盖旧的文件
def w_save_txt(file, word):
    with open(file, 'w', encoding='utf-8') as fp:
        fp.write(word)


# 附加到文件末尾不换行，新增内容
def a_save_txt(file, word):
    with open(file, 'a', encoding='utf-8') as fp:
        fp.write(word)


# 附加到文件末尾换行，新增内容
def an_save_txt(file, word):
    with open(file, 'a', encoding='utf-8') as fp:
        fp.write(word + '\n')

# 附加到文件末尾换行，新增内容
def ann_save_txt(file, word):
    with open(file, 'a', encoding='utf-8') as fp:
        fp.write('\n\n'+word+'\n')


# 如果需要以二进制方式保存文件，需要在mode后面加上字符"b"，比如"rb""wb"等，图片常用wb
def save_file(file, info):
    with open(file, 'wb') as fp:
        fp.write(info)


# 以二进制方式打开文件
def get_file(file):
    with open(file, 'rb') as fp:
        return fp.read()


# 按行读取文件（去除空格，筛选匹配的数据）file-文件，word-开头的文字
def get_line(file,words,stop_word):
    data = []
    with open(file, "r", encoding='utf-8') as fp:
        for line in fp.readlines():
            line = line.strip()
            #for word in words:
            if line.split() and line[0:len(words)] == words:
                data.append(line)
            elif line.split() and line.split(' ')[0] == stop_word:
                break
    #print(data)
    return data


# 按行读取文件（去除空格，筛选匹配的数据）file-文件，words-开头的文字
def get_lines(file,words):
    data = []
    with open(file, "r", encoding='utf-8') as fp:
        for line in fp.readlines():
            line = line.strip()
            for word in words:
                if line.split() and line[0:len(word)] == word:
                    data.append(line)
                elif line.split() and line[0:2] == '跳出':
                    break
    #print(data)
    return data


# 按行读取文件（组合成一个字符串）
def get_line_str(file,key):
    line_str = ''
    with open(file, "r", encoding='utf-8') as fp:
        for line in fp.readlines():
            line = str(line.strip().split(key)[0])
            line_str =  line_str +',' + line
    print(line_str)
    return line_str

# 按行读取文件（组合成一个字符串）
def get_lines_str(file):
    line_str = ''
    with open(file, "r", encoding='utf-8') as fp:
        for line in fp.readlines():
            line = line.strip()
            line_str =  line_str + line
    print(line_str)
    return line_str

# 不以word开头
def get_line_out(file,word):
    data = []
    with open(file, 'r',encoding= 'utf-8') as fp:
        for line in fp.readlines():
            line = line.lstrip().replace(' ','').replace('\n','')
            if line[0:1] != '#':
                data.append(line)
    return(data)

# 以固定字符串切割
def get_split_info(file,word):
    data = []
    with open(file, 'r',encoding= 'utf-8') as fp:
        for line in fp.readlines():
            row =[]
            info = line.split(word)
            print(info)
            row.append(info[0])
            row.append(info[1])
            data.append(row)
    return (data)


# 大文件切割
def cut_file(file,num):
    file_path = os.path.dirname(file)
    file_name = os.path.basename(file)
    with open(file, 'r',encoding= 'utf-8') as fp:
        info = fp.readlines()
        print(len(info))                      # 行数
        n = int(math.ceil(len(info) /num))         # 每个文件的行数
        for i in range(num):
            file = file_path + '\\' +str(i) + file_name
            for j in range(n):
                print(i*n+j+1)
                print(info[i*n+j+1])
                an_save_txt(file,info[i*n+j+1])

def get_stocks():
    stock = 'stock_top_two'
    path = 'F:\\PythonProject\股票\\'
    file = path + 'cacho.sql'
    stock_file = path + stock +'.sql'
    with open(file, 'r',encoding= 'utf-8') as fp:
        info = fp.readlines()
        for line in info:
            if stock in line:
                print(line)
                an_save_txt(stock_file,line)

# 按行读取文件（组合成dict）file-文件，s_word-开头的文字,e_word-结束字符，p_word-分割字符
def get_dict(file,s_word,e_word,p_word):
    story_dict = {}
    with open(file, "r", encoding='utf-8') as fp:
        for line in fp.readlines():
            line = line.strip()
            if line.split() and line[0:len(s_word)] == s_word:
                data= line.replace(s_word,'').split(e_word)[0].split(p_word)
                story_dict[data[0]]= data[1]  # 字典赋值
    #print(story_dict)
    return story_dict

# 替换文件中的字符, file:需要处理的文件
def replace_txt(file):
    words = {'false':'False','null':'None','true':'True'}
    with open (file, "r", encoding='utf-8') as fp:
        txt = fp.read()
        for key in words:
            if key in txt:
                txt = txt.replace(key, words[key])
        return(eval(txt))



if __name__ == '__main__':
    #get_dict('F:\PythonProject\Python\\file\\story_dict.txt','\'',',',': ')
    get_lines_str('E:\\lingwei\\OpenSSL-data\\java-public.pem')
    #cut_file('F:\PythonProject\股票\\stock_tradeinfo_total.sql',10)
    #get_stocks()
    #replace_txt('F:\\alibaba\json\\')
